package com.example.shippxy.thread;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.IOUtils;
import com.example.shippxy.constant.Constant;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.*;
import java.util.Map;
import java.util.Set;

public class SocketThread implements Runnable{

    private static Integer PORT = Constant.PORT;

    @Override
    public void run() {
        ServerSocket serverSocket = null;

        while (!Thread.currentThread().isInterrupted()){
            try {
                serverSocket = buildServerSocket();
                serverSocket.setSoTimeout(20000);
                Thread.sleep(2000);
                while (!Thread.currentThread().isInterrupted()) {
                    Socket socket = null;
                    BufferedWriter writer = null;
                    try {
                        socket = serverSocket.accept();
                        socket.setKeepAlive(true);
                        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                        while (socket.getKeepAlive()) {
                            Set<Map.Entry<String, JSONObject>> set = Constant.shipsMap.entrySet();
                            for (Map.Entry<String,JSONObject> entry: set) {
                                writer.write(entry.getValue().toString() + "\n");
                                writer.flush();
                                Thread.sleep(100);
                            }
                            Thread.sleep(5000);
                        }
                    } catch (SocketTimeoutException e) {
                        serverSocket.close();
                        serverSocket = buildServerSocket();
                        continue;
                    } catch (Exception e1){
                        Thread.sleep(3000);
                    }finally{
                        IOUtils.close(writer);
                        IOUtils.close(socket);
                    }
                }
            } catch (Exception e1) {
                try {
                    Thread.sleep(15*1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } finally {
                IOUtils.close(serverSocket);
                serverSocket = null;
            }
        }
    }

    private ServerSocket buildServerSocket() throws IOException, SocketException {
        ServerSocket serverSocket = new ServerSocket(PORT); // 端口号
        serverSocket.setSoTimeout(20000);
        return serverSocket;
    }
}
